package com.pachong.android.framework.commonui;

import android.content.res.ColorStateList;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.pachong.android.framework.R;
import com.pachong.android.frameworkbase.customviews.BadgeRadioButton;
import com.pachong.android.frameworkbase.customviews.SlideControlableViewPager;
import com.pachong.android.frameworkbase.utils.DimensionUtil;

import java.util.List;

public abstract class RadioButtonBottomTabFragment extends Fragment implements CompoundButton.OnCheckedChangeListener,
        ViewPager.OnPageChangeListener {
    private List<PageInfo> mPages;
    private SlideControlableViewPager mPager = null;
    private RadioGroup mRgBottomMenu = null;
    private View mRootView = null;

    public abstract List<PageInfo> createPages();
    /*private List<PageInfo> createPages() {
        Fragment main1Frag = new Main1Fragment();
        Fragment main2Frag = new Main2Fragment();
        Fragment main3Frag = new Main3Fragment();

        String[] TITLES = new String[]{"page1", "page2", "page3"};
        final int[] ICONS = new int[]{R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher};

        List<PageInfo> pageList = new ArrayList<>();
        pageList.add(new YourRadioButtonBottomTabFragment.PageInfo(main1Frag, TITLES[0], ICONS[0]));
        pageList.add(new YourRadioButtonBottomTabFragment.PageInfo(main2Frag, TITLES[1], ICONS[1]));
        pageList.add(new YourRadioButtonBottomTabFragment.PageInfo(main3Frag, TITLES[2], ICONS[2]));

        Fragment main6Frag = new TemplateImageVPFragment();
        pageList.add(new YourRadioButtonBottomTabFragment.PageInfo(main6Frag, TITLES[2], ICONS[2]));

        return pageList;
    }*/


 /*   public static RadioButtonBottomTabFragment newInstance() {
        RadioButtonBottomTabFragment fragment = new RadioButtonBottomTabFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }*/


    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putSerializable("currentPage", mPager.getCurrentItem());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_bottom_menu_main, container, false);
        mPages = createPages();
        mRgBottomMenu = (RadioGroup) mRootView.findViewById(R.id.rg_bottom);
        addToRadioGroup(inflater, container);

        FragmentStatePagerAdapter adapter = new PageAdapter(getActivity().getSupportFragmentManager());
        mPager = (SlideControlableViewPager) mRootView.findViewById(R.id.vp_home);
        mPager.setAdapter(adapter);
        mPager.setOnPageChangeListener(this);
        mPager.setOffscreenPageLimit(mPages.size());
        mPager.setPageSlideEnabled(false);
        int currPage = savedInstanceState == null ? 0 : savedInstanceState.getInt("currentPage", 0);
        setCurrentPage(currPage);
        return mRootView;
    }


    private void addToRadioGroup(LayoutInflater inflater, ViewGroup container) {
        for (PageInfo pageInfo : mPages) {
            pageInfo.rbtn = createRadioButton(inflater, container, pageInfo);
            RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams(0,
                    RadioGroup.LayoutParams.MATCH_PARENT);
            lp.weight = 1.0f;
            mRgBottomMenu.addView(pageInfo.rbtn, lp);
        }
    }

    private BadgeRadioButton createRadioButton(LayoutInflater inflater, ViewGroup container, PageInfo pageInfo) {
        BadgeRadioButton ret = (BadgeRadioButton) inflater.inflate(R.layout.bottom_menu_radio_button, container, false);
        ret.setOnCheckedChangeListener(this);
        ret.setText(pageInfo.text);
        Drawable drawable = getResources().getDrawable(pageInfo.iconId);
        ret.setCompoundDrawables(null, drawable, null, null);
        return  ret;
    }

    /**
     * RadioButton 的点击被截获的listener
     * 有些需求要在RadioButton被点击之后做需求判断，然后决定要不要check this radio button
     *
     * @param index    radio button 的位置， 不包含用户自己添加的
     * @param listener
     */
    public void setRadioButtonInterruptCheckedListener(int index, BadgeRadioButton.OnInterruptCheckedListener listener) {
        View view = mRgBottomMenu.getChildAt(index);

        if (view instanceof BadgeRadioButton) {
            BadgeRadioButton btn1 = (BadgeRadioButton) view;
            btn1.setOnInterruptCheckedListener(listener);

        } else {
            throw new RuntimeException("index 指向的控件不是RadioButton类型");
        }
    }


    /**
     * 在某个位置添加一个按钮
     *
     * @param view
     * @param index
     */
    public void addButton(View view, int index) {
        mRgBottomMenu.addView(view, index);
    }


    public void addButton(View view, int index, RadioGroup.LayoutParams lp) {
        mRgBottomMenu.addView(view, index, lp);
    }


    /**
     * 动态添加RadioButton
     * @deprecated 改成xml来布局，维护性比较好，此代码保留
     * @param pageInfo
     * @return
     */
    private BadgeRadioButton createRadioBtn(PageInfo pageInfo) {
        BadgeRadioButton rbtn = new BadgeRadioButton(getActivity());
        rbtn.setOnCheckedChangeListener(this);
        rbtn.setText(pageInfo.text);
        ColorStateList csl = getResources().getColorStateList(R.color.bottom_menu_fragment_text);
        rbtn.setTextColor(csl); // 设置文字的颜色

        int size = DimensionUtil.dip2px(getActivity(), 22);
        Drawable drawable = getResources().getDrawable(pageInfo.iconId);
        drawable.setBounds(0, 0, size, size);// 必须设置图片大小，否则不显示
        rbtn.setCompoundDrawables(null, drawable, null, null);
        rbtn.setCompoundDrawablePadding(DimensionUtil.dip2px(getActivity(), 6));

        // Set style
        rbtn.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 11.0f);
        rbtn.setLines(1);
        rbtn.setButtonDrawable(android.R.color.transparent);
        rbtn.setBackgroundDrawable(null);
        rbtn.setGravity(Gravity.CENTER);
        rbtn.setPadding(0, 0, 0, 0); // 文本会居中
        return rbtn;
    }


    private void addPage(Fragment fragment, String text, int iconRes) {
        PageInfo pageInfo = new PageInfo(fragment, text, iconRes);
        mPages.add(pageInfo);
    }

    class PageAdapter extends FragmentStatePagerAdapter {

        public PageAdapter(FragmentManager fm) {
            super(fm);
        }


        @Override
        public Fragment getItem(int position) {
            return mPages.get(position).fragment;
        }


        @Override
        public CharSequence getPageTitle(int position) {
            return mPages.get(position).text;
        }


        @Override
        public int getCount() {
            return mPages.size();
        }
    }


    @Override
    public void onPageScrollStateChanged(int arg0) {

    }


    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }


    @Override
    public void onPageSelected(int posi) {
        RadioButton rbtn = mPages.get(posi).rbtn;
        if (rbtn != null && !rbtn.isChecked()) {
            mRgBottomMenu.check(rbtn.getId());
        }

    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            for (int i = 0; i < mPages.size(); i++) {
                if (buttonView == mPages.get(i).rbtn) {
                    if (mPager.getCurrentItem() != i) {
                        mPager.setCurrentItem(i, true);
                    }
                }
            }
        }

    }

    public int getCurrentPage() {
        return mPager.getCurrentItem();
    }

    public void setCurrentPage(int currPage) {
        if (mPager != null && mPager.getCurrentItem() != currPage) {
            mPager.setCurrentItem(currPage);
        }
        onPageSelected(currPage);
    }

    public static class PageInfo {

        public PageInfo(Fragment fragment, String text, int iconRes) {
            this.fragment = fragment;
            this.iconId = iconRes;
            this.text = text;
        }

        Fragment fragment;
        int iconId;
        String text;
        RadioButton rbtn;
    }

}
